package tools

// MatchFrameFooter 匹配帧尾
func MatchFrameFooter(data []byte, suffix []byte) (b bool) {
	var l1 = len(data)
	var l2 = len(suffix)
	if l2 == 0 {
		return
	}
	if l1 < l2 {
		return
	}
	b = true
	for i := l2; i > 0; i-- {
		if suffix[l2-i] != data[l1-i] {
			b = false
		}
	}
	return
}

// MatchFrameHeader 匹配帧头
func MatchFrameHeader(data []byte, prefix []byte) (b bool) {
	var l1 = len(data)
	var l2 = len(prefix)
	if l2 == 0 {
		return
	}
	if l1 < l2 {
		return
	}
	b = true
	for i := 0; i < l2; i++ {
		if prefix[i] != data[i] {
			b = false
		}
	}
	return
}

// Crc16 Modbus 信息 CRC16 校验
func Crc16(data []byte) uint16 {
	var crc uint16 = 0xFFFF
	for _, b := range data {
		crc ^= uint16(b)
		for i := 0; i < 8; i++ {
			if crc&0x0001 != 0 {
				crc >>= 1
				crc ^= 0xA001 // Polynomial for Modbus (0x8005 reversed byte order)
			} else {
				crc >>= 1
			}
		}
	}
	return crc
}

// GetCrc16Result 获取crc16 校验结果值
func GetCrc16Result(b []byte) []byte {
	checksum := Crc16(b)
	res := []byte{byte(checksum & 0xFF), byte(checksum >> 8)}
	return res
}

// AppendCrc16 原始数据后面添加校验数据
func AppendCrc16(b []byte) []byte {
	checksum := Crc16(b)
	b = append(b, byte(checksum&0xFF), byte(checksum>>8))
	return b
}

// CheckCRC16 CRC16校验
func CheckCRC16(a []byte) bool {
	if len(a) < 2 {
		return false
	}
	c1 := Crc16(a[0 : len(a)-2])
	c2 := BytesToUint16(a[len(a)-2:], "little")
	//fmt.Println("------------ crc16 = ", c1, ":", c2)
	return c1 == c2
}

func CheckCRC16Custom(buffer []byte, checkStart, checkEnd, start, end int) bool {
	if len(buffer) < 2 {
		return false
	}
	c1 := Crc16(buffer[checkStart : checkEnd+1])
	c2 := BytesToUint16(buffer[start:end+1], "little")
	//fmt.Println("------------ crc16 = ", c1, ":", c2)
	return c1 == c2
}
